<?php
class CurrentUser extends User implements ArrayAccess {

    public function __construct() {
        parent::__construct();
        if (isset($_COOKIE['user_id']) && isset($_COOKIE['hash'])) {
            //получаем все данные пользователя по id
            $userdata = $this->model->getUserDataById($_COOKIE['user_id']);

            //если данные не совпадают
            if (!$userdata || ($userdata['user_hash'] !== $_COOKIE['hash']) || ($userdata['user_id'] !== $_COOKIE['user_id'])) {
                setcookie("user_id", "", time() - 3600 * 24 * 30 * 12, "/");
                setcookie("hash", "", time() - 3600 * 24 * 30 * 12, "/");
                $this->isLogged = false;
            } else {
                $this->isLogged = true;
                $this->init($userdata);
                $this->model->updateUserStatus($userdata['user_id']);
            }
        } else {
            $this->isLogged = false;
        }
    }

    public function setLoginStrategy($strategy) {
        $this->strategy = $strategy;
    }

    public function doRegistration($reg_data) {
        $email = $reg_data['user_email'];
        $password = md5(md5(trim($reg_data['user_password'])));
        $nickname = $reg_data['user_nickname'];
        $this->model->addUser($email, $nickname, $password);
        return true;
    }

    public function doLogin($auth_data, $caller = null) {
        //если уже залогинен -> иди на главную страничку
        //$args = func_get_args();
        //dump($args);
        //$current_stategy = @$args[0];
        //получаем ссылку на объект выбранной стратегии
        $this->registry->load->library('class.LoginFabric.php', 'user');
        $strategy = LoginFabric::getLoginStrategy($auth_data['strategy']);
        //устанавливаем стратегию
        $this->setLoginStrategy($strategy);
        //пробуем логиниться
        return $this->strategy->doLogin($this, $auth_data);

    }

    public function doLogout() {
        setcookie("user_id", "", time() + 60 * 60 * 24 * 30, "/");
        setcookie("hash", "", time() + 60 * 60 * 24 * 30, "/");

        $this->isLogged = false;
    }

    public function setStrategy(LoginStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function offsetExists($offset) {
        return isset($this->$offset);
    }

    public function offsetGet($offset) {
        Registry::getInstance()->load->library('class.AnotherUser.php', 'user');
        try {
            $user = new AnotherUser($offset);    
        } catch (Exception $exc) {
            $user = false;
        }
        return $user;
    }

    public function offsetSet($offset, $value) {
        $this->$offset = $value;
    }

    public function offsetUnset($offset) {
        unset($this->$offset);
    }


}

?>